package com.gxa.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxa.common.R;
import com.gxa.entity.DistrictSysRole;
import com.gxa.entity.DistrictSysUser;
import com.gxa.mapper.RoleMapper;
import com.gxa.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;


    /**
     * 分页查询所有角色
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public R queryAllRolesByPage(int currentPage, int pageSize) {
        R r = new R();
        try{
            Page<DistrictSysRole> page = PageHelper.startPage(currentPage,pageSize);
            List<DistrictSysRole> districtSysRoleList = roleMapper.selectAllRoles();
            int count = (int)page.getTotal();
            r.setCode(200);
            r.setMsg("查询成功！");
            r.setCount(count);
            r.setData(districtSysRoleList);
        }catch (Exception e){
            e.printStackTrace();
            r.setCode(500);
            r.setMsg("系统异常,查询失败,请联系管理员");
        }
        return r;
    }

    /**
     * 添加角色
     * @param districtSysRole
     * @return
     */
    @Override
    @Transactional
    public R addRole(DistrictSysRole districtSysRole) {
        R r = new R();
        try{
            //先查询该角色是否存在
            DistrictSysRole selectedDistrictSysRole = roleMapper.selectRoleByName(districtSysRole.getRoleName());
            if(selectedDistrictSysRole == null){
                //要添加的角色不存在，进行添加
                roleMapper.insertRole(districtSysRole);
                //还要向角色和权限的关系表sys_role_permission中添加记录
                String permissionIds = districtSysRole.getPermissionIds();
                if(permissionIds != null || !"".equals(permissionIds)){
                    String[] permissionIdsArray = permissionIds.split(",");
                    for(String permissionId : permissionIdsArray){
                        Map<String,Integer> map = new HashMap<>();
                        map.put("roleId", districtSysRole.getRoleId());
                        map.put("permissionId", Integer.parseInt(permissionId));
                        roleMapper.insertRoleAndPermission(map);
                    }
                    r.setCode(200);
                    r.setMsg("添加成功！");
                    return r;
                }
            }
            r.setCode(1001);
            r.setMsg("添加失败！角色已存在");
            return r;
        }catch (Exception e){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            r.setCode(500);
            r.setMsg("系统异常,添加失败,请联系管理员");
            return r;
        }
    }

    /**
     * 根据角色编号删除角色信息
     * @param roleId
     * @return
     */
    @Override
    @Transactional
    public R deleteRole(int roleId) {
        R r = new R();
        try {
            //先根据角色编号查询对应的账号信息
            List<DistrictSysUser> districtSysUserList = roleMapper.selectDistrictUsersByRoleId(roleId);
            if(districtSysUserList.size() == 0){
                //先删除角色表district_sys_role中的对应的信息
                roleMapper.deleteRole(roleId);
                //再根据角色编号删除角色和权限关系表sys_role_permission中对应的信息
                roleMapper.deleteRoleAndPermission(roleId);
                r.setCode(200);
                r.setMsg("删除成功！");
            }else {
                r.setCode(1002);
                r.setMsg("该角色关联了若干数据，不支持删除！");
            }
        }catch (Exception e){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            r.setCode(500);
            r.setMsg("系统异常,删除失败,请联系管理员");
        }
        return r;
    }

    /**
     * 根据角色编号查询角色详情
     * @param roleId
     * @return
     */
    @Override
    public R queryRoleDetail(int roleId) {
        R r = new R();
        try{
            DistrictSysRole districtSysRole = roleMapper.selectRoleById(roleId);
            r.setCode(200);
            r.setData(districtSysRole);
            r.setMsg("查询成功！");
        }catch (Exception e){
            e.printStackTrace();
            r.setCode(500);
            r.setMsg("系统异常,查询失败,请联系管理员");
        }
        return r;
    }

    /**
     * 编辑角色信息
     * @param districtSysRole
     * @return
     */
    @Override
    @Transactional
    public R editRole(DistrictSysRole districtSysRole) {
        R r = new R();
        try {
            //首先删除该角色信息
            deleteRole(districtSysRole.getRoleId());
            //然后添加角色信息
            roleMapper.insertRoleWithFixedId(districtSysRole);
            //还要向角色和权限的关系表sys_role_permission中添加记录
            String permissionIds = districtSysRole.getPermissionIds();
            if(permissionIds != null || !"".equals(permissionIds)){
                String[] permissionIdsArray = permissionIds.split(",");
                for(String permissionId : permissionIdsArray){
                    Map<String,Integer> map = new HashMap<>();
                    map.put("roleId", districtSysRole.getRoleId());
                    map.put("permissionId", Integer.parseInt(permissionId));
                    roleMapper.insertRoleAndPermission(map);
                }
            }
            r.setCode(200);
            r.setMsg("修改成功！");
        }catch (Exception e){
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            r.setCode(500);
            r.setMsg("系统异常,修改失败,请联系管理员");
        }
        return r;
    }

    /**
     * 查询所有角色
     * @return
     */
    @Override
    public R queryAllRoles() {
        R r = new R();
        try{
            List<DistrictSysRole> districtSysRoleList = roleMapper.selectAllRoles();
            r.setCode(200);
            r.setMsg("查询成功");
            r.setData(districtSysRoleList);
        }catch (Exception e){
            e.printStackTrace();
            r.setCode(500);
            r.setMsg("系统异常,查询失败,请联系管理员");
        }
        return r;
    }
}
